package com.jialanmo.zhihudaily.ui.news;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.Toast;

import com.jialanmo.zhihudaily.R;
import com.jialanmo.zhihudaily.data.model.News;

import butterknife.BindView;
import butterknife.ButterKnife;

public final class NewsActicity extends AppCompatActivity implements NewsContract.View {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.activity_news_webview_body)
    WebView mWebView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        ButterKnife.bind(this);

        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        int id = getIntent().getIntExtra(News.NEWS_ID, 0);
        NewsContract.Presenter presenter = new NewsPresenter(this, id);

        presenter.start();
    }

    @Override
    public void showNews(News news) {
        StringBuilder sb = new StringBuilder("<html><head>");
        for (String css : news.getCss()) {
            sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"").append(css).append("\" />");
        }
        sb.append("</head><body style=\"height:100%;width:100%;\">");
        sb.append(news.getBody().replace("<div class=\"img-place-holder\"></div>", "<div class=\"img-place-holder\"><div class=\"img-wrap\" style=\"max-height:200px;overflow:hidden;position:relative;\"><img src=\"" + news.getImage() + "\" style=\"margin-top:-80px;\"/><span class=\"img-source\" style=\"position:absolute;bottom:10px;color:white;\">" + news.getImageSource() + "</span><h1 class=\"headline-title\" style=\"position:absolute;color:white;z-index:1;\">" + news.getTitle() + "</h1><div style=\"position:absolute;top:0;width:100%;height:100%;background:linear-gradient(to bottom, rgba(0,0,0,0) 25%, rgba(0,0,0,0.6) 100%);\"></div></div></div>"));
        for (String js : news.getJs()) {
            sb.append("<script src=\"").append(js).append("\" />");
        }
        sb.append("</body></html>");
        mWebView.loadDataWithBaseURL(null, sb.toString(), "text/html", "UTF-8", null);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return false;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void showMessage(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}
